
import { _decorator, Component, SpriteFrame, Sprite } from 'cc';
import i18n from './LanguageData';
import { bundleTool } from '../bundleTool';
const { ccclass, property, executeInEditMode, menu } = _decorator;

@ccclass('LocalizedSpriteItem')
class LocalizedSpriteItem {
	@property
		language: string = 'zh';

	@property({
		type: SpriteFrame,
	})
		spriteFrame: SpriteFrame | null = null;
}

@ccclass('LocalizedSprite')
@menu('i18n/LocalizedSprite')
@executeInEditMode
export class LocalizedSprite extends Component {
	sprite: Sprite | null = null;

	@property({ visible: true })
		isDynamic: boolean = false;

	@property({ type: LocalizedSpriteItem, visible: function () { return !this.isDynamic } })
		spriteList = [];

	@property({ visible: function () { return this.isDynamic } })
		bundle: string = '';

	onLoad() {
		if (!i18n.ready) {
			i18n.init('zh');
		}

		this.fetchRender();
	}

	fetchRender() {
		const sprite = this.getComponent('cc.Sprite') as Sprite;

		if (sprite) {
			this.sprite = sprite;
			this.updateSprite();

			return;
		}
	}

	updateSprite() {
		if (this.isDynamic) {
			bundleTool.instance().loadAsyncFromBundle(this.bundle, `${i18n.langPath}/${i18n._language}/${this.sprite.spriteFrame.name}/spriteFrame`, SpriteFrame).then((data) => {
				this.sprite.spriteFrame = data;
			});
		} else {
			for (let i = 0; i < this.spriteList.length; i++) {
				const item = this.spriteList[i];

				// @ts-ignore
				if (item.language === i18n._language) {
					// @ts-ignore
					this.sprite.spriteFrame = item.spriteFrame;
					break;
				}
			}
		}

	}
}
